<?php
class EnumsSelectorWidget extends YWidget{
	public $code 	= null;		//enums的code
	public $type 	= 'checkbox'; //可选值：checkbox | radio | select
	public $name 	= '';
	public $id 		= null;
	public $values 	= null; //当前值，可以是字符或数组
	
	public function run(){
		if($this->values == null){
			$this->values = array();
		}else{
			if(!is_array($this->values)){
				$this->values = explode(',', $this->values);
			}
		}
	
		if(empty($this->code)){
			echo CHtml::tag('span', array('class'=>'error'), 'EnumsSelectorWidget.code 未设置！');return;
		}
		$enums = EnumsModel::getEnums($this->code);
		if(empty($enums)){
			echo CHtml::tag('span', array('class'=>'error'), 'EnumsSelectorWidget.code=' . $this->code . ' 不存在！');return;
		}
		
		$render_fun = '_render_' . $this->type;
		$this->$render_fun($enums);
	}
	
	private function _render_select($enums){
		if(empty($this->id)){
			$this->id = 'EnumsSelectorWidget_' . rand(10000, 99999);
		}
		echo '<select name="' . $this->name . '" id="' . $this->id . '">';
		foreach ($enums as $val=>$name){
			if(in_array($val, $this->values)){
				//选中
				echo '<option value="' . $val . '" selected="selected">' . $name . '</option> ';
			}else{
				echo '<option value="' . $val . '">' . $name . '</option> ';
			}
		}
		echo '</select>';
	}
	
	private function _render_radio($enums){
		foreach ($enums as $val=>$name){
			if(in_array($val, $this->values)){
				//选中
				echo '<label><input type="radio" checked="checked" name="' . $this->name . '" value="' . $val . '"/>' . $name . '</label> ';
			}else{
				echo '<label><input type="radio" name="' . $this->name . '" value="' . $val . '"/>' . $name . '</label> ';
			}
		}
	}
	
	private function _render_checkbox($enums){
		foreach ($enums as $val=>$name){
			if(in_array($val, $this->values)){
				//选中
				echo '<label><input type="checkbox" checked="checked" name="' . $this->name . '" value="' . $val . '"/>' . $name . '</label> ';
			}else{
				echo '<label><input type="checkbox" name="' . $this->name . '" value="' . $val . '"/>' . $name . '</label> ';
			}
		}
	}
}

?>